<?php

namespace app\common\model\supplier;

use app\common\enum\order\OrderSourceEnum;
use app\common\model\BaseModel;
use app\common\model\plus\coupon\UserCoupon as UserCouponModel;
use app\common\model\supplier\CommissionConfig;
use app\common\model\supplier\CommissionProduct;
use app\common\model\supplier\SupplierCommissionWithdrawal;
use app\api\model\product\Product;
use app\shop\model\order\Order;
use app\shop\model\supplier\Supplier as SupplierModel;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

class SupplierCommission extends BaseModel
{


    protected $append = [
        'order_source_text',
    ];

    /**
     * 订单来源
     * @param $value
     * @return array
     */
    public function getOrderSourceTextAttr($value, $data)
    {
        return OrderSourceEnum::data()[$data['order_source']]['name'];
    }
    /**
     *添加商品分佣记录
     * createProductData
     * @param $list
     * SupplierCommission|\think\Model
     * static
     * @return SupplierCommission|\think\Model
     * @Author kevin
     * @date 2024/4/23 17:20
     */
    public static function createProductData($list,$supplier_commission)
    {
        //获取该订单所有的商品id
        $product_ids = array_column($list,'product_id');

        //获取该订单的商品设置的分佣金额
        $commission_config_array = (new Product())->  where('product_id','in',$product_ids) -> column('product_name,commission_config_id','product_id');

        $commission_config_list = (new CommissionConfig()) -> select();
        $product_data = [];

        if(!$commission_config_array || !$commission_config_list){
            return ;
        }

        if(self::where('order_id',$supplier_commission['order_id']) -> count()){
            return ;
        }

        foreach ($commission_config_array as $v){
            foreach ($commission_config_list as $v1){
                if($v['commission_config_id'] == $v1['commission_config_id']){
                    $product_id = $v['product_id'];
                    $data['product_id'] = $product_id;
                    $data['rate'] = $v1['rate'];
                    $data['commission_config_id'] = $v['commission_config_id'];
                    $product_data[$product_id] = $data;
                }
            }

        }

        $total_commission = 0;
        foreach ($list as $key => $value){
            $list[$key]['commission_money'] = 0;
            $list[$key]['commission_rate'] = 0;
            $list[$key]['app_id'] = self::$app_id;
            if(isset($product_data[$value['product_id']])){
                $rate = $product_data[$value['product_id']]['rate'];
                $commission = round($rate * $value['total_pay_price']/100,2);
                $total_commission += $commission;
                $list[$key]['commission_money'] = $commission;
                $list[$key]['commission_rate'] = $rate;
            }
            unset($list[$key]['order_product_id']);
        }
        $supplier_commission['commission'] = $total_commission;
        $supplier_commission['app_id'] = self::$app_id;
        (new CommissionProduct()) -> saveAll($list);

        return self::create($supplier_commission);
    }

    /**
     * 分佣明细
     * getSupplierCommissionList
     * @param $shop_supplier_id
     * @param $data
     * @param $type 1= 查询列表 ，2=只查询统计,3=导出列表
     * array
     * @return array
     * @throws \think\db\exception\DbException
     * static
     * @throws \think\db\exception\DbException
     * @Author kevin
     * @date 2024/4/29 15:51
     */
    public static function getSupplierCommissionList($shop_supplier_id='',$data,$type=1){

        $map = [];
        $map2 = [];
        $where = [];
        $where2 = [];
        if($shop_supplier_id){
            $map[] = ['shop_supplier_id','=',$shop_supplier_id];
            $map2[] = ['shop_supplier_id','=',$shop_supplier_id];

            $where[] = ['shop_supplier_id','=',$shop_supplier_id];
            $where2[] = ['shop_supplier_id','=',$shop_supplier_id];
        }

        if(isset($data['order_no']) && $data['order_no']){
            $map[] = ['order_no','=',$data['order_no']];
        }

        //搜索时间段
        if (isset($data['create_time']) && $data['create_time'] != '') {
            $sta_time = strtotime(array_shift($data['create_time']));
            $end_time = strtotime(array_pop($data['create_time'])) + 24*3600-1;
            $map[] = ['order_create_time','>=',$sta_time];
            $map[] = ['order_create_time','<=',$end_time];
        }

        $total_commission = self::where($map2) -> sum('commission'); //分佣总额
        $total_refund_money = self::where($map2) -> sum('refund_money');//退款总额

        $total_price = self::where($map2) -> sum('pay_price'); //订单总额
        $total_price -= $total_refund_money;

        $list = [];
        if($type==1){
            $list = self::where($map) -> field('*,pay_time pay_time_text,order_create_time order_create_time_text')-> order('commission_id desc') -> with(['product.image','user','system_coupons']) ->paginate($data);
            foreach ($list as $key => $value){
                $list[$key]['is_first_order'] = Order::getFirstOrderId($value) == $value["order_id"];
                $list[$key]['fee'] = round($value['pay_price'] * 0.006,2);
            }
        }

        if($type==3){
            $list = self::where($map) -> field('*,pay_time pay_time_text,order_create_time order_create_time_text')-> order('commission_id desc') -> with(['product.image','user','system_coupons']) ->select();
            foreach ($list as $key => $value){
                $list[$key]['is_first_order'] = Order::getFirstOrderId($value) == $value["order_id"];
                $list[$key]['fee'] = round($value['pay_price'] * 0.006,2);
            }
        }


        $where[] = ['status','=',1];
        $where2[] = ['status','=',0];

        $income_money = (new SupplierCommissionWithdrawal()) -> where($where) -> sum('money'); //已收入金额(已提现金额)

        $be_confirmed_money = (new SupplierCommissionWithdrawal()) -> where($where2) -> sum('money'); //已收入金额(已提现金额)


        $withdrawal_money = self::getWithdrawalMoney($shop_supplier_id);
        $fee = $total_price * 0.006;
        $res_data['total_commission'] = round($total_commission,2);
        $res_data['be_confirmed_money'] = round($be_confirmed_money,2);
        $res_data['fee'] = round($fee,2);
        $res_data['withdrawal_money'] = round($withdrawal_money,2);
        $res_data['income_money'] = round($income_money,2);
        $res_data['total_price'] = round($total_price,2);
        $res_data['shop_supplier_id'] = $shop_supplier_id;
        $res_data['list'] = $list;

        return $res_data;
    }

    public static function getSupplierCommissionListData($params,$type=1){
        // 供应商列表
        $model = new SupplierModel;
        $list = $model->getListData($params,$type);
        foreach ($list as $key => $value){
            $data = self::getSupplierCommissionList($value['shop_supplier_id'],[],2);
            $list[$key]['total_commission'] = $data['total_commission'];
            $list[$key]['fee'] = $data['fee'];
            $list[$key]['withdrawal_money'] = $data['withdrawal_money'];
            $list[$key]['income_money'] = $data['income_money'];
            $list[$key]['total_price'] = $data['total_price'];
            $list[$key]['be_confirmed_money'] = $data['be_confirmed_money'];
        }
        return $list;
    }

    /**
     * 订单导出
     */
    public static function exportCommission($list)
    {
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        //列宽
        $sheet->getColumnDimension('A')->setWidth(15);
        $sheet->getColumnDimension('B')->setWidth(20);
        $sheet->getColumnDimension('F')->setWidth(20);
        $sheet->getColumnDimension('G')->setWidth(20);
        $sheet->getColumnDimension('I')->setWidth(15);
        $sheet->getColumnDimension('J')->setWidth(20);
        $sheet->getColumnDimension('K')->setWidth(20);
        $sheet->getColumnDimension('m')->setWidth(20);

        //设置工作表标题名称
        $sheet->setTitle('商户分佣明细');

        $sheet->setCellValue('A1', '商户ID');
        $sheet->setCellValue('B1', '所属地区');
        $sheet->setCellValue('C1', '商户名称');
        $sheet->setCellValue('D1', '联系人');
        $sheet->setCellValue('E1', '联系电话');
        $sheet->setCellValue('F1', '订单总额');
        $sheet->setCellValue('G1', '分佣总额（元）');
        $sheet->setCellValue('H1', '累计收入(元)');
        $sheet->setCellValue('I1', '支付费率(0.6%;元)');
        $sheet->setCellValue('J1', '可提现(元)');


        //填充数据
        $index = 0;
        $startline = 2;
        foreach ($list as $user) {
            $sheet->setCellValue('A' . ($index + $startline), $user['shop_supplier_id']);
            $sheet->setCellValue('B' . ($index + $startline), "\t" . $user['region_name'] . "\t");
            $sheet->setCellValue('C' . ($index + $startline), "\t" . $user['name'] . "\t");
            $sheet->setCellValue('D' . ($index + $startline), $user['link_name']);
            $sheet->setCellValue('E' . ($index + $startline), $user['link_phone']);
            $sheet->setCellValue('F' . ($index + $startline), $user['total_price']);
            $sheet->setCellValue('G' . ($index + $startline), $user['total_commission']);
            $sheet->setCellValue('H' . ($index + $startline), $user['income_money']);
            $sheet->setCellValue('I' . ($index + $startline), $user['fee']);
            $sheet->setCellValue('J' . ($index + $startline), $user['withdrawal_money']);


            $index++;
        }

        //保存文件
        $filename = iconv("UTF-8", "GB2312//IGNORE", '商户分佣明细') . '-' . date('YmdHis') . '.xlsx';

        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
        exit();
    }

    /**
     * 获取可提现金额
     * getWithdrawalMoney
     * @param $shop_supplier_id
     * @param $type
     * float
     * static
     * @return float
     * @Author kevin
     * @date 2024/5/21 15:41
     */
    public static function getWithdrawalMoney($shop_supplier_id='',$type=1){
        $map = [];
        if($shop_supplier_id){
            $map[] = ['shop_supplier_id','=',$shop_supplier_id];
        }

        if($type == 1){
            $three_time_ago = strtotime(date('Y-m-d',strtotime('-3 days')))+24*3600-1;//T+3//查询三天前的数据
            $map[] = ['order_create_time','<=',$three_time_ago];
        }


        $total_commission = self::where($map) -> sum('commission'); //分佣总额
        $total_price = self::where($map) -> sum('pay_price'); //订单总额
        $total_refund_money = self::where($map) -> sum('refund_money'); //订单退款
        $total_price -= $total_refund_money;

        $where = [];
        if($shop_supplier_id){
            $where[] = ['shop_supplier_id','=',$shop_supplier_id];
        }

        $where[] = ['status','=',1];
        $income_money = (new SupplierCommissionWithdrawal()) -> where($where) -> sum('money'); //已收入金额(已提现金额)
        $withdrawal_money = $total_price*(1-0.006) - $total_commission - $income_money;
        return round($withdrawal_money,2);


    }



    public  function withdrawal($shop_supplier_id =0,$money=0,$shop_user_id=0,$status=0,$payment_images=''){
        //可提现金额
        $balance = self::getWithdrawalMoney($shop_supplier_id);
        $result_data = [];
        if($money <= 0){
            $result_data['msg'] = '请输入提现金额';
            $result_data['status'] = 0;
            return $result_data;
        }
        if($balance < $money){
            $result_data['msg'] = '可提现金额不足';
            $result_data['status'] = 0;
            return $result_data;
        }

        $data['shop_supplier_id'] = $shop_supplier_id;
        $data['shop_user_id'] = $shop_user_id;
        $data['money'] = $money;
        $data['status'] = $status;
        $data['payment_images'] = $payment_images;
        $map = [];
        $map[] = ['shop_supplier_id','=',$shop_supplier_id];
        $map[] = ['status','=',0];
        $msg = '提现成功';
        if($status == 0){
            $msg = '提现申请已提交，请等待审核';
        }
//        if((new SupplierCommissionWithdrawal()) -> where($map) -> count()  && $status == 0){
//
//            $result_data['msg'] = '您有未确认的订单';
//            $result_data['status'] = 0;
//            return $result_data;
//        }

        if(SupplierCommissionWithdrawal::createData($data)){
            $result_data['msg'] = $msg;
            $result_data['status'] = 1;
            return $result_data;
        }else{
            $result_data['msg'] = '提现失败';
            $result_data['status'] = 0;
            return $result_data;
        }
    }

    public static function refund($order_id,$refund_money=0)
    {

        self::where('order_id',$order_id) -> update(['refund_money' => $refund_money,'commission' => 0]);
    }

    /**
     * 订单商品列表
     */
    public function product()
    {
        return $this->hasMany('app\\common\\model\\supplier\\CommissionProduct', 'order_id', 'order_id');
    }

    /**
     * 订单商品列表
     */
    public function user()
    {
        return $this->hasOne('app\\common\\model\\user\\User', 'user_id', 'user_id');
    }

    public function getPayTimeTextAttr($value)
    {
        return $value?date('Y-m-d',$value):'';
    }
    public function getOrderCreateTimeTextAttr($value)
    {
        return $value?date('Y-m-d',$value):'';
    }


    public function systemCoupons()
    {
        return $this->hasOne(UserCouponModel::class, 'user_coupon_id', 'coupon_id_sys')->visible(['user_coupon_id','coupon_type','name','reduce_price']);
    }



}